<template>
  <div class="approval-template">
    <!--    <div class="card">-->
    <!--      <el-button type="primary" size="mini" @click="handleCreate">创建审批模版</el-button>-->
    <!--    </div>-->

    <div class="card">
      <el-table
        v-loading="loading"
        :data="list"
        border
        stripe
      >
        <el-table-column prop="name" label="审批模版名称" align="center">
          <template v-slot="{ row }">
            {{ row?.templates[0] ? row.templates[0]?.name : '默认模版' }}
          </template>
        </el-table-column>
        <el-table-column prop="type" label="审批类型" align="center">
          <template v-slot="{ row }">
            {{ row.name }}
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" align="center">
          <template v-slot="{ row }">
            {{ timeFormat(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template v-slot="{ row }">
            <el-button type="primary" size="mini" @click="handleEdit(row)">编辑</el-button>
            <!--            <el-button type="danger" size="mini" @click="handleDelete(row)">删除</el-button>-->
          </template>
        </el-table-column>
      </el-table>

      <div class="approval-template__page">
        <Pagination
          style="margin-top: 0; padding: 0;"
          :total="total"
          :limit="params.paginate"
          @pagination="pagination"
        />
      </div>
    </div>

    <UserSelectModal
      v-model="users"
      :visible.sync="showUserSelectModal"
    />
  </div>
</template>
<script>
import {
  getApprovalType,
  getApprovalTemplatesList,
  deleteApprovalTemplates,
  createApprovalTemplates
} from '@/api/approvalFlow'
import { sleep, timeFormat } from '@/utils'
import Pagination from '@/components/Pagination/index.vue'
import UserSelectModal from '@/components/UserSelectModal/UserSelectModal.vue'
import { defaultNode } from '@/views/approvalFlow/js/defaultNode'

export default {
  name: '',
  components: { Pagination, UserSelectModal },
  data() {
    return {
      approvalType: [],
      list: [],
      params: {
        page: 1,
        paginate: 10,
        name: ''
      },
      total: 0,
      loading: false,
      timeFormat,
      showUserSelectModal: false,
      users: []
    }
  },
  created() {
    this.getApprovalType()
    this.getApprovalTemplatesList()
  },
  methods: {
    async getApprovalTemplatesList() {
      this.loading = true
      try {
        const res = await getApprovalTemplatesList(this.params)
        console.log('res getApprovalTemplatesList--------->', res)
        this.list = res.data.data
        this.total = res.data.total
      } catch (error) {
        this.$message.error('审批模版获取失败')
      } finally {
        await sleep(300)
        this.loading = false
      }
    },

    async getApprovalType() {
      try {
        const res = await getApprovalType()
        this.approvalType = res.data
      } catch (error) {
        this.$message.error('审批类型获取失败')
      }
    },

    handleCreate() {
      this.$router.push({ path: '/workflows' })
    },

    getEventType(eventId) {
      return this.approvalType.find(item => item.id === eventId / 1)?.name
    },

    pagination(page) {
      this.params.page = page.page
      this.params.paginate = page.limit
      this.getApprovalTemplatesList()
    },

    async handleEdit(row) {
      console.log('row --------->', row)
      let id = row.templates.length ? row.templates[0].id : null
      if (row.templates.length === 0) {
        const data = {
          name: '默认模版',
          type_id: row.id,
          content: JSON.stringify(defaultNode),
          nodes: JSON.stringify([])
        }
        const res = await this.createDefaultTemplate(data)
        id = res.data.id
      }

      this.$router.push({ path: '/workflows', query: { id }})
    },

    async createDefaultTemplate(data) {
      const res = await createApprovalTemplates(data)
        .catch((error) => {
          this.$message.error(error?.response?.data?.message || '编辑失败')
        })

      return res
    },

    handleDelete(row) {
      this.$confirm('确定要删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await this.deleteApprovalTemplates(row.id)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },

    async deleteApprovalTemplates(id) {
      try {
        const res = await deleteApprovalTemplates(id)
        this.$message.success('删除成功')
        await this.getApprovalTemplatesList()
      } catch (error) {
        this.$message.error(error?.response?.data?.message || '删除失败')
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.approval-template {
  padding: 20px;

  &__page {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
  }
}
</style>
